//
//  HLMatchLabelViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/6/6.
//

#import "HLMatchLabelViewController.h"
#import "HLMatchRequest.h"
#import "HLMatchLabelCell.h"
#import "HLMatchFateTipView.h"


@interface HLMatchLabelViewController ()

@property (nonatomic, strong) UIImageView *backgroundView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) NSString *localLabelKey;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) NSArray *currentLabels;
@property (nonatomic, strong) QMUIButton *coinView;
@property (nonatomic, strong) QMUIButton *matchButton;

@end

@implementation HLMatchLabelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.localLabelKey = [NSString stringWithFormat:@"%@_local_label_key", HLRunTime.shareInstance.mine.userId];
    
    NSString *labels = [[NSUserDefaults standardUserDefaults] stringForKey:_localLabelKey];
    if (labels.length > 0){
        self.currentLabels = [labels componentsSeparatedByString:@","];
    } else {
        self.currentLabels = @[@"beauty", @"hot", @"new_reg"];
    }
    
    self.backgroundView = [[UIImageView alloc] initWithImage:UIImageMake(@"invite_background")];
    [self.view insertSubview:_backgroundView atIndex:0];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    self.request = [[HLMatchRequest alloc] initWithType:HLMatchTypeLabelList params:@{}];
    self.request.delegate = self;
    [self requestInit];
}

- (void)viewDidDisappear:(BOOL)animated
{
    NSArray *codes = [[self.datasources qmui_filterWithBlock:^BOOL(HLMatchLabelModel *  _Nonnull item) {
        return item.isSelected;
    }] qmui_mapWithBlock:^NSString * _Nonnull(HLMatchLabelModel * _Nonnull item, NSInteger index) {
        return item.tagCode;
    }];
    if (codes.count > 0){
        NSString *labelString = [codes componentsJoinedByString:@","];
        [[NSUserDefaults standardUserDefaults] setObject:labelString forKey:self.localLabelKey];
    }
    [super viewDidDisappear:animated];
}

- (void)requestInit
{
    [self showEmptyView];
    [self.emptyView.loadingView startAnimating];
    [self.emptyView setTextLabelText:@"加载中..."];
    [self.request start];
}

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithCustomView:({
        QMUIButton *saveButton = [[QMUIButton alloc] init];
        [saveButton setTitle:@"匹配规则" forState:UIControlStateNormal];
        [saveButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
        [saveButton.titleLabel setFont:UIFontMediumMake(14)];
        saveButton;
    })];
    
    self.navigationItem.rightBarButtonItem = saveItem;
}


- (UIImage *)qmui_navigationBarBackgroundImage
{
    return [UIImage qmui_imageWithColor:UIColorClear];
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return UIColorWhite;
}

- (nullable UIColor *)qmui_titleViewTintColor
{
    return UIColorWhite;
}

- (BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view
{
    return YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}


- (void)initCollectionView
{
    [super initCollectionView];
    
    CGFloat itemW = (SCREEN_WIDTH-50)/3.0;
    CGFloat itemH = itemW * 1.28;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(itemW, itemH);
    layout.minimumLineSpacing = 8.0;
    layout.minimumInteritemSpacing = 8.0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    [self.collectionView registerClass:[HLMatchLabelCell class] forCellWithReuseIdentifier:[HLMatchLabelCell identifyCell]];
    [self.collectionView setCollectionViewLayout:layout];
    self.collectionView.backgroundColor = UIColorClear;
    
    self.titleLabel = [[UILabel alloc] qmui_initWithFont:UIFontBoldMake(20) textColor:UIColorWhite];
    _titleLabel.text = @"选择喜欢的标签类型";
    [self.view addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(18);
        make.top.mas_equalTo(NavigationContentTopConstant + 12);
    }];
    
    self.detailLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(14) textColor:UIColorWhite];
    _detailLabel.text = @"即可为你找到心仪的TA";
    [self.view addSubview:_detailLabel];
    [_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleLabel);
        make.top.equalTo(_titleLabel.mas_bottom).offset(8);
    }];
    
    self.bottomView = [[UIView alloc] init];
    _bottomView.backgroundColor = [UIColor qmui_colorWithHexString:@"#232A35"];
    _bottomView.layer.masksToBounds = YES;
    _bottomView.layer.cornerRadius = 20;
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(20);
        make.height.mas_equalTo(98 + (SafeAreaInsetsConstantForDeviceWithNotch.bottom));
    }];
    
    self.matchButton = [[QMUIButton alloc] init];
    [_matchButton setTitle:@"开始匹配" forState:UIControlStateNormal];
    [_matchButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_matchButton.titleLabel setFont:UIFontMediumMake(16)];
    [_matchButton setBackgroundColor:HLMainColor];
    [_matchButton setCornerRadius:22];
    [_matchButton setContentEdgeInsets:UIEdgeInsetsMake(12, 62, 12, 62)];
    [_matchButton addTarget:self action:@selector(matchAction) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_matchButton];
    [_matchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(16);
    }];
    
    
    self.coinView = [[QMUIButton alloc] init];
    [_coinView setImage:UIImageMake(@"home_flow_coin") forState:UIControlStateNormal];
    [_coinView setTitle:@"199/分钟" forState:UIControlStateNormal];
    [_coinView setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_coinView.titleLabel setFont:UIFontMediumMake(14)];
    [_coinView setImagePosition:QMUIButtonImagePositionLeft];
    [_coinView setSpacingBetweenImageAndTitle:4];
    [_bottomView addSubview:_coinView];
    [_coinView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.equalTo(_matchButton);
    }];
    
}
- (void)matchAction
{
    MJWeakSelf;
    NSArray *codes = [[self.datasources qmui_filterWithBlock:^BOOL(HLMatchLabelModel *  _Nonnull item) {
        return item.isSelected;
    }] qmui_mapWithBlock:^NSString * _Nonnull(HLMatchLabelModel * _Nonnull item, NSInteger index) {
        return item.tagCode;
    }];
    if (codes.count > 0){
        NSString *labelString = [codes componentsJoinedByString:@","];
        [[NSUserDefaults standardUserDefaults] setObject:labelString forKey:self.localLabelKey];
        [HLMatchFateTipView showWithLabel:labelString callback:^(BOOL canMatch) {
            if (canMatch){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf matchAction];
                });
            }
        }];
    } else {
        [QMUITips showWithText:@"请选择标签"];
    }
}

- (void)layoutCollectionView
{
    [super layoutCollectionView];
    CGFloat top = NavigationContentTopConstant + 90;
    self.collectionView.frame = CGRectMake(16, top, SCREEN_WIDTH-32, SCREEN_HEIGHT-(top+SafeAreaInsetsConstantForDeviceWithNotch.bottom + 78));
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datasources.count;
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    HLMatchLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[HLMatchLabelCell identifyCell] forIndexPath:indexPath];
    cell.model = self.datasources[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HLMatchLabelModel *model = self.datasources[indexPath.row];
    model.isSelected = !model.isSelected;
    [collectionView reloadData];
    
    
}

- (void)requestFinished:(__kindof YTKBaseRequest *)request
{
    [super requestFinished:request];
    
    HLMatchRequest *labelRequest = (HLMatchRequest *)request;
    
    NSArray *labelList = [[labelRequest labelList] qmui_mapWithBlock:^HLMatchLabelModel * _Nonnull(HLMatchLabelModel * _Nonnull item, NSInteger index) {
        if ([self.currentLabels containsObject:item.tagCode]){
            item.isSelected = YES;
        }
        return item;
    }];
    [self.datasources addObjectsFromArray:labelList];
    if (labelList.count < [HLListPageSize integerValue] && self.datasources.count > 0){
        [self noMordDataWithFooterRefresh];
    }
    
    if (self.datasources.count == 0){
        [self.emptyView setLoadingViewHidden:YES];
        [self.emptyView setImage:UIImageMake(@"empty_icon_8")];
        [self.emptyView setTextLabelText:@"招呼相册列表为空"];
    } else {
        [self hideEmptyView];
    }
    
    [self.collectionView reloadData];
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request
{
    [super requestFailed:request];
}

@end
